#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int flag = 0;
void* PrintA(void* arg)
{
    while(1)
    {
        pthread_mutex_lock(&mutex);
        if(flag == 0)
        {
            printf("A\n");
            sleep(1);
            flag = 1;
            //发送条件变量
            pthread_cond_signal(&cond);
        }
        else
        {
            //等待条件变量
            pthread_cond_wait(&cond,&mutex);
        }
        pthread_mutex_unlock(&mutex);
    }
}

void* PrintB(void* arg)
{
    while(1)
    {
        pthread_mutex_lock(&mutex);
        if(flag == 1)
        {
            printf("B\n");
            sleep(1);
            flag = 0;
            pthread_cond_signal(&cond);
        }
        else
        {
            pthread_cond_wait(&cond,&mutex);
        }
        pthread_mutex_unlock(&mutex);
    }
}


int main()
{
    pthread_t thread1;
    pthread_t thread2;

    //pthread_cond_init();
    pthread_create(&thread1,NULL,PrintA,NULL);
    pthread_create(&thread2,NULL,PrintB,NULL);

    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);

    pthread_mutex_destroy(&mutex);

    pthread_cond_destroy(&cond);
}